package com.zirenx.sys.controller;

import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.zirenx.annotation.RouteMapping;
import com.zirenx.common.controller.BaseController;
import com.zirenx.common.controller.IController;
import com.zirenx.sys.model.SysDict;
import com.zirenx.sys.model.SysUser;
import com.zirenx.sys.service.SysDictService;
import com.zirenx.utils.LogUtils;
import com.zirenx.utils.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import java.util.List;

@RouteMapping("/sys/dict")
public class SysDictController extends BaseController implements IController{

	@Inject
	SysDictService sysDictService;

	@RequiresPermissions("sys:dict:index")
	@Override
	public void index() {
		// TODO Auto-generated method stub
		
	}

	@RequiresPermissions("sys:dict:add")
	@Override
	public void add() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void save() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void edit() {
		// TODO Auto-generated method stub
		SysDict bean = new SysDict();
		try {
			String id = get("id");
			bean = bean.dao().findById(id);
		}catch (Exception e){
			LogUtils.error(this.getClass(),e);
		}
		setAttr("bean",bean);
	}

	@Override
	public void update() {
		// TODO Auto-generated method stub

	}

	@RequiresPermissions("sys:dict:add")
	@Override
	public void remove() {
		// TODO Auto-generated method stub
		R r = R.ok();
		try {
			String id = get("id");
			new SysDict().findById(id).delete();
		} catch (Exception e) {
			LogUtils.error(this.getClass(),e);
			r = R.error();
		}
		renderJson(r);
	}

	@Override
	public void dataAjax() {
		R r = R.ok();
		try {
			SysDict bean = getBean(SysDict.class,"bean");

			SqlPara sqlPara = new SqlPara();
			String sql = "select * from " + bean.getTableName() + " bean where 1=1 ";

			sql += appendSearch(sqlPara);
			sql += " order by bean.id desc";
			sqlPara.setSql(sql);

			Page<SysDict> p = bean.paginate(getPageNumber(), getPageSize(), sqlPara);

			List<SysDict> list = p.getList();

			r.put("rows", list);
			r.put("total", p.getTotalRow());
		} catch (Exception e) {
			LogUtils.error(this.getClass(),e);
			r = R.error(); 
		}
		renderJson(r);
	}

	@RequiresPermissions("sys:dict:batchRemove")
	@Override
	public void batchRemove() {
		// TODO Auto-generated method stub
		R r = R.ok();
		try {
			String[] ids = getParaValues("ids");
			if (ids!=null && ids.length>0){
				SysDict bean = new SysDict();
				for (String id : ids){
					bean.findById(id).delete();
				}
			}
		} catch (Exception e) {
			LogUtils.error(this.getClass(),e);
			r = R.error();
		}
		renderJson(r);
	}

}
